package view;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;


import javax.swing.DebugGraphics;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;

import tools.Tab;
import tools.TabIO;

import adaptors.TabReference;
import adaptors.TabTreeNodeAdaptor;
import com.cloudgarden.layout.AnchorConstraint;
import com.cloudgarden.layout.AnchorLayout;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class LocalTabsPanel extends javax.swing.JPanel implements TreeSelectionListener, Serializable, ActionListener, PropertyChangeListener, MouseListener {
	private static final long serialVersionUID = 1L;
	private JSplitPane tabViewSplitPane;
	private JButton editTabButton;
	private JTextArea tabTextArea;
	private JButton deleteButton;
	private JScrollPane bandScrollPane;
	private JScrollPane songScrollPane;
	private JTree bandTree;
	private View parent;
	private JButton openButton;
	private TabReference selectedTab;
	
	
	public LocalTabsPanel(View parent) {
		super();
		this.parent = parent;
		initGUI();
	}
	
	private void initGUI() {
		try {
			this.setPreferredSize(new java.awt.Dimension(784, 427));
			AnchorLayout thisLayout = new AnchorLayout();
			this.setLayout(thisLayout);
			{
				editTabButton = new JButton();
				this.add(editTabButton, new AnchorConstraint(24, 97, 78, 69, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				editTabButton.setPreferredSize(new java.awt.Dimension(22, 23));
				editTabButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("view/icons/edit-icon.png")));
				editTabButton.addActionListener(this);
				editTabButton.setActionCommand("editButton");
				editTabButton.setBorderPainted(false);
				editTabButton.setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION);
				editTabButton.setToolTipText("Edit Selected Tab...");
			}

			{
				songScrollPane = new JScrollPane();
			}
			
			{
		  		DefaultMutableTreeNode root = new DefaultMutableTreeNode("Tabs");

		  		DefaultMutableTreeNode child;
		  		DefaultMutableTreeNode grandChild;
		    
		  		Set<String> bands = parent.controller.tabLib.getAllBandEntries();
		  		
		  		Iterator<String> itr = bands.iterator();
		  		
		  		for(; itr.hasNext();) {
		  			String bandName = itr.next();
		  			child = new DefaultMutableTreeNode(bandName);
		  			
		  			root.add(child);

		  			TreeMap<String, TabReference> bandTabMap = parent.controller.tabLib.findBand(bandName);
		  			Set<String> tabKeySet = bandTabMap.keySet();
		  			Iterator<String> tabItr = tabKeySet.iterator();
		  			
		  			for(; tabItr.hasNext();) {
		  				String t = tabItr.next();
		  				grandChild = new TabTreeNodeAdaptor(bandTabMap.get(t));
		  				child.add(grandChild);
		  			}

		  		}
		  		
		  		bandTree = new JTree(root);
		  		bandTree.setPreferredSize(new Dimension(200, 400));
		  		bandTree.addTreeSelectionListener(this);
		  		bandTree.addMouseListener(this);
		  		bandTree.setForeground(parent.getPrefFGColor());
		  		bandTree.setBackground(parent.getPrefBGColor());
			}
			
			{
				bandScrollPane = new JScrollPane();
				bandScrollPane.setViewportView(bandTree);
		  		bandScrollPane.setMinimumSize(new Dimension(100, 100));
		  		bandScrollPane.setPreferredSize(new Dimension(200, 100));
			}
			
			{
				openButton = new JButton();
				this.add(openButton, new AnchorConstraint(24, 47, 76, 15, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				openButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("view/icons/open-icon.png")));
				openButton.setActionCommand("openTab");
				openButton.setBorderPainted(false);
				openButton.setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION);
				openButton.setToolTipText("Open Selected Tab...");
				openButton.setPreferredSize(new java.awt.Dimension(25, 22));
				openButton.addActionListener(this);				
			}
			
			{
				tabViewSplitPane = new JSplitPane();
				this.add(tabViewSplitPane, new AnchorConstraint(87, 1000, 1001, 0, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				tabViewSplitPane.setPreferredSize(new java.awt.Dimension(784, 390));
				tabViewSplitPane.setDividerLocation(parent.getLocalTabSplitPosition());
				tabViewSplitPane.addPropertyChangeListener(this);
				{
					bandScrollPane = new JScrollPane();
					tabViewSplitPane.add(bandScrollPane, JSplitPane.LEFT);
				}
				tabViewSplitPane.add(songScrollPane, JSplitPane.RIGHT);
				{
					tabTextArea = new JTextArea();
					tabTextArea.setFont(parent.getPreferredFont());
					tabTextArea.setForeground(parent.getPrefFGColor());
					tabTextArea.setBackground(parent.getPrefBGColor());
					tabTextArea.setEditable(false);
					tabTextArea.setMargin(new java.awt.Insets(2, 10, 2, 1));
				}
				songScrollPane.setViewportView(tabTextArea);
			}
			{
				deleteButton = new JButton();
				this.add(deleteButton, new AnchorConstraint(24, 154, 76, 129, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
				deleteButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("view/icons/delete-icon.png")));
				deleteButton.setActionCommand("deleteTab");
				deleteButton.setBorderPainted(false);
				deleteButton.setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION);
				deleteButton.setToolTipText("Delete Selected Tab");
				deleteButton.setPreferredSize(new java.awt.Dimension(20, 22));
				deleteButton.addActionListener(this);				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void updateBandTree()	{
		System.out.println("Band Tree Update");
  		DefaultMutableTreeNode root = new DefaultMutableTreeNode("Tabs");

  		DefaultMutableTreeNode child;
  		DefaultMutableTreeNode grandChild;
    
  		Set<String> bands = parent.controller.tabLib.getAllBandEntries();
  		
  		Iterator<String> itr = bands.iterator();
  		
  		for(; itr.hasNext();) {
  			String bandName = itr.next();
  			child = new DefaultMutableTreeNode(bandName);
  			
  			root.add(child);

  			TreeMap<String, TabReference> bandTabMap = parent.controller.tabLib.findBand(bandName);
  			Set<String> tabKeySet = bandTabMap.keySet();
  			Iterator<String> tabItr = tabKeySet.iterator();
  			
  			for(; tabItr.hasNext();) {
  				String t = tabItr.next();
  				grandChild = new TabTreeNodeAdaptor(bandTabMap.get(t));
  				child.add(grandChild);
  			}


  		}
  		
  		bandTree = new JTree(root);
  		DefaultTreeCellRenderer dtcr = new DefaultTreeCellRenderer();
  		Icon i = new ImageIcon(getClass().getClassLoader().getResource("view/icons/tab-icon.png"));
  		dtcr.setLeafIcon(i);
  		bandTree.setCellRenderer(dtcr);
  		bandTree.addTreeSelectionListener(this);
  		bandTree.addMouseListener(this);
  		bandScrollPane.setMinimumSize(new Dimension(100, 100));
  		bandScrollPane.setPreferredSize(new Dimension(200, 100));
		bandScrollPane.setViewportView(bandTree);  		
  		bandTree.repaint();
	}
	
	
	public void openTab()	{
		if( selectedTab == null )	{
			JOptionPane.showMessageDialog(null, "No tab selected!");
			return;
		}
		
		Tab t = TabIO.readTabFile(parent.getTabRootPath()+selectedTab.getPath());
		if( t != null )	{
			tabTextArea.setText(t.getTabText());
			tabTextArea.setCaretPosition(0);
			tabTextArea.setFont(parent.getPreferredFont());
		}
		else	{
			JOptionPane.showMessageDialog(null, "Couldn't load selected tab:\n" + selectedTab);
		}
	}



	public void setTabSplitPosition(int position) {
		tabViewSplitPane.setDividerLocation(position);
	}
	
	///////////////////////////////
	// Listeners from here down! //
	///////////////////////////////
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		if( e.getActionCommand() == "openTab" )	{
			openTab();
		}
		else if( e.getActionCommand() == "deleteTab" )	{
			if( selectedTab == null )	{
				JOptionPane.showMessageDialog(null, "No tab selected!");
				return;
			}
			
			int result = JOptionPane.showConfirmDialog(null, 
						"Are you sure you want to delete this tab?\n" + 
						selectedTab.getBandName() + " - " + selectedTab.getSongName());
			
			if( result == JOptionPane.NO_OPTION || result == JOptionPane.CANCEL_OPTION )
				return;

			if( parent.deleteTab(selectedTab) )	{
				JOptionPane.showMessageDialog(null, "Tab was removed from library!");
			}
			else	{
				JOptionPane.showMessageDialog(null, "Couldn't remove tab from library for whatever reason!\n**OopsieS!**");
			}
		}
		else if( e.getActionCommand() == "editButton" )	{
			if( selectedTab == null )	{
				JOptionPane.showMessageDialog(null, "No tab selected!");
				return;
			}

			parent.editTab(selectedTab);
		}
		
	}

	@Override
	public void propertyChange(PropertyChangeEvent arg0) {		
		if( arg0.getSource() instanceof JSplitPane )	{
			JSplitPane sourceSplitPane = (JSplitPane)arg0.getSource();
			String propertyName = arg0.getPropertyName();
			if (propertyName.equals(JSplitPane.LAST_DIVIDER_LOCATION_PROPERTY) )	{
				parent.saveLocalTabSplitPosition(sourceSplitPane.getDividerLocation());
				System.out.println("sourceSplitPane.getDividerLocatioN: " + sourceSplitPane.getDividerLocation());
			}
		}
	}
	
	@Override
	public void valueChanged(TreeSelectionEvent arg0) {
		if( (bandTree.getLastSelectedPathComponent()) != null )	{
			Object o = bandTree.getLastSelectedPathComponent();
			if( o instanceof TabTreeNodeAdaptor )	{
				TabTreeNodeAdaptor ttna = (TabTreeNodeAdaptor)o;
				selectedTab = ttna.getPayload();
				System.out.println("Selected tab: " + selectedTab);
			}
			else	{
				System.out.println("Folder: " + bandTree.getLastSelectedPathComponent().toString());
				selectedTab = null;
			}
		}
	}
	
	@Override
	public void mouseClicked(MouseEvent arg0) {
		if( arg0.getSource() instanceof JTree )	{
			if( arg0.getClickCount() == 2 )
				if( selectedTab != null )
					openTab();
		}
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	
	
	
}
